/*
 * @Author: pardon110
 * @Date: 2024-03-22 18:12:30
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-22 18:36:27
 * @FilePath: \days7\geerpc\day1\main\main.go
 * @Description:
 */
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net"
	"time"

	// "time"

	"days7.test/geerpc/codec"
	"days7.test/geerpc/day1"
)

func main() {
	log.SetFlags(0)

	addr := make(chan string)
	go startServer(addr)

	// like rpc client
	conn, _ := net.Dial("tcp", <-addr)
	defer func() {
		_ = conn.Close()
	}()

	time.Sleep(time.Second)
	// send options
	_ = json.NewEncoder(conn).Encode(day1.DefaultOption)
	cc := codec.NewGobCodec(conn)

	// send request & receive response
	for i := 0; i < 5; i++ {
		h := &codec.Header{
			ServiceMethod: "Foo.Sum",
			Seq:           uint64(i),
		}
		_ = cc.Write(h, fmt.Sprintf("day1 rpc req %d", h.Seq))
		_ = cc.ReadHeader(h)
		var reply string
		_ = cc.ReadBody(&reply)
		log.Println("reply:", reply)
	}

}

func startServer(addr chan<- string) {
	// pick a free port
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Fatal("network error: ", err)
	}
	log.Println("start rpc server on ", l.Addr())

	addr <- l.Addr().String()

	// 调用监听
	day1.Accept(l)
}
